package com.vsclouds.mp.config.shiro.authc;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with Software Dept.
 * <p> {@code RetryLimitHashedCredentialsMatcher}
 * 登录身份认证器
 *
 * @author : tianbaolei
 * @date : 2020-06-18 16:23
 * Description:
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> cache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager, String hashAlgorithmName, int hashIterations, boolean storeCredentialsHexEncoded) {
        super.setHashAlgorithmName(hashAlgorithmName);
        super.setHashIterations(hashIterations);
        super.setStoredCredentialsHexEncoded(storeCredentialsHexEncoded);
        if (cacheManager != null) {
            cache = cacheManager.getCache("passwordRetryCache");
        }
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        boolean matches = super.doCredentialsMatch(token, info);
        String username = String.valueOf(token.getPrincipal());
        if (matches) {
            cache.remove(username);
        } else {
            // 登录失败后，统计登录次数，默认登录5次错误，限定超过一定次数不允许登录则不允许再登录
            // String key = "RetryLimit:" + username;
            AtomicInteger atomicInteger = cache.get(username);
            if (atomicInteger == null) {
                atomicInteger = new AtomicInteger();
                cache.put(username, atomicInteger);
            }
            int retryCount = atomicInteger.getAndIncrement();
            if (retryCount > 4) {
                // 重试5次，超过5次半小时内不允许登录，计数从0开始，判断依据为4，缓存保存的是已经重试的次数
                throw new ExcessiveAttemptsException("username password try to many times");
            }
        }
        return matches;
    }
}
